/* 
date : 2020/05/31
author : wang yong
notes : 批量文件改名，操作语句： node rename.js p 1000 C:/Users/wangyong/Desktop/png
*/
'use strict';
var fs = require('fs');
var ments = process.argv.splice(2); // 命令行传递参数[ 'p', '1000', './png' ]
var head = ments[0] ? ments[0] : "p";
var keys = ments[1] ? Number(ments[1]) : 1000;
var directory = ments[2] ? ments[2] : "C:/Users/wangyong/Desktop/png";
var format = head + "$";
rename(directory, format);

function rename(fileName, formation) {
    fs.readdir(fileName,
        function (err, data) {
            data.forEach(function (item) {
                keys++;
                var f;
                var type = item.split('.');
                type = "." + type[type.length - 1];
                if (formation.length === 1) {
                    f = keys;
                } else if (formation.startsWith('$')) { // 前缀
                    f = keys + formation.split('$')[1];
                } else if (formation.endsWith('$')) { // 后缀
                    f = formation.split('$')[0] + keys;
                } else { // 中缀
                    var arr = formation.split('$');
                    f = arr[0] + keys + arr[1];
                }
                fs.rename(directory + '/' + item, directory + '/' + f + type,
                    function (err) {
                        if (err) {
                            throw err;
                        } else {
                            console.log(f + type)
                        }
                    })
            })
        })
};